﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BPM.Entity;
using System.Data.Entity;
using Webdiyer.WebControls.Mvc;
using BPM.Common;

namespace BPM.Service
{
	public class PurchaseOrderService : ServiceBase<PurchaseOrder>
	{
		protected override IQueryable<PurchaseOrder> PrepareToQuery(DbSet<PurchaseOrder> set)
		{
			return base.PrepareToQuery(set)
				.Include(o => o.ItemList)
				.Include(o => o.MaterialInDeliveryList)
				.Include("MaterialInDeliveryList.ItemList")
				.Include(o => o.Barcode);
		}

		protected override void EnableLazyLoadingCore(PurchaseOrder entity)
		{
			base.EnableLazyLoadingCore(entity);

			foreach (var item in entity.ItemList)
			{
				item.EnableLazyLoading = true;
			}
		}

		public Result Approve(int id)
		{
			var c = this.NewContext();
			var order = c.Set<PurchaseOrder>().FirstOrDefault(o => o.Id == id);
			if (order == null) return "id参数错误。";
			order.IsApproved = true;
			return c.Save();
		}

		/// <summary>
		/// 分页获取待验证的采购单
		/// </summary>
		/// <param name="pageIndex"></param>
		/// <param name="pageSize"></param>
		/// <returns></returns>
		public override PagedList<PurchaseOrder> GetAll(int pageIndex, int pageSize)
		{
			var q = this.Query();
			var result = q.Where(p => !p.IsApproved)
				.OrderByDescending(p => p.CreatedTime)
				.ToPagedList(pageIndex, pageSize);
			return EnableLazyLoading(result);
		}

		/// <summary>
		/// 根据当前采购员 查询他创建的采购单
		/// </summary>
		/// <param name="pageIndex"></param>
		/// <param name="pageSize"></param>
		/// <param name="user"></param>
		/// <returns></returns>
		public PagedList<PurchaseOrder> GetAllByBuyer(int pageIndex, int pageSize, User user)
		{
			var q = this.Query();
			var result = q.Where(p => p.CreatorId == user.Id)
				.OrderByDescending(p => p.CreatedTime)
				.ToPagedList(pageIndex, pageSize);
			return EnableLazyLoading(result);
		}

		public IList<PurchaseOrder> GetActiveOrders()
		{
			var result = this.Query().Where(o => !o.IsFinished && o.IsApproved)
				.OrderByDescending(o => o.CreatedTime)
				.ToList();
			return this.EnableLazyLoading(result);
		}

		public PagedList<PurchaseOrder> GetApprovedOrders(int pageIndex, int pageSize)
		{
			var result = this.Query().Where(o => o.IsApproved)
				.OrderByDescending(o => o.CreatedTime)
				.ToPagedList(pageIndex, pageSize);
			return this.EnableLazyLoading(result);
		}
	}
}